<template>
  <div class="group-container">
    <!-- 顶部操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="showAddGroupDialog">
        <el-icon><Plus /></el-icon>
        <span>新增</span>
      </el-button>
    </div>

    <!-- 标签切换 -->
    <el-tabs v-model="currentTab" class="group-tabs">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="班级" name="class"></el-tab-pane>
      <el-tab-pane label="战队" name="team"></el-tab-pane>
    </el-tabs>

    <!-- 新增组对话框 -->
    <el-dialog v-model="addGroupDialogVisible" title="新增组" width="30%">
      <el-form :model="addGroupForm" label-width="80px">
        <el-form-item label="组名" required>
          <el-input v-model="addGroupForm.groupName" placeholder="请输入组名" clearable />
        </el-form-item>
        <el-form-item label="组类型" required>
          <el-radio-group v-model="addGroupForm.groupType">
            <el-radio label="班级" />
            <el-radio label="战队" />
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addGroupDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddGroup" :loading="adding">确定</el-button>
      </template>
    </el-dialog>

    <!-- 所有班级部分 -->
    <el-card
        v-for="(groupItem, index) in filteredGroupData"
        :key="groupItem.group.groupId"
        class="group-card"
        v-if="filteredGroupData.length > 0"
    >
      <template #header>
        <div class="card-header">
          <span>{{ groupItem.group.groupName }}</span>
          <el-button
              type="danger"
              size="small"
              @click.stop="handleDeleteGroup(groupItem.group.groupId, groupItem.group.groupName)"
              :loading="deletingId === groupItem.group.groupId"
          >
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </div>
      </template>

      <div class="user-list">
        <!-- 现有用户列表 -->
        <el-card
            v-for="user in groupItem.users"
            :key="user.userId"
            class="user-card"
            shadow="hover"
            @click="handleClick(groupItem.group.groupName)"
        >
          <div class="user-content">
            <el-avatar :size="40" :src="user.avatarUrl" />
            <span class="user-name">{{ user.userName }}</span>
          </div>
        </el-card>

        <!-- 添加用户标签 -->
        <el-card class="add-user-card" shadow="hover" @click="openUserSelection(groupItem.group.groupId)">
          <div class="add-user-content">
            <el-icon :size="24"><Plus /></el-icon>
            <span>添加用户</span>
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- 用户选择对话框 -->
    <el-dialog v-model="userDialogVisible" title="选择用户" width="70%">
      <el-input
          v-model="searchQuery"
          placeholder="输入用户名搜索"
          clearable
          @input="handleSearch"
          style="margin-bottom: 20px"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <div class="select-user-list">
        <el-card
            v-for="user in filteredUserList"
            :key="user.userId"
            class="select-user-card"
            :class="{ 'is-selected': selectedUserIds.includes(user.userId) }"
            @click="toggleUserSelection(user.userId)"
            shadow="hover"
        >
          <div class="select-user-content">
            <el-avatar :size="40" :src="user.avatarUrl" />
            <span>{{ user.userName }}</span>
          </div>
        </el-card>
      </div>
      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddUsers">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Plus, Delete, Search } from '@element-plus/icons-vue';
import Group from "@/api/Backend/GroupApi.ts";
import Alluser from "@/api/Backend/AllUserApi.ts";
import { ref, computed, onMounted } from 'vue';

const groupData = ref([]);
const adding = ref(false);
const deletingId = ref('');
const userDialogVisible = ref(false);
const allUserList = ref([]);
const filteredUserList = ref([]);
const selectedUserIds = ref<number[]>([]);
const currentGroupId = ref('');
const searchQuery = ref('');
const currentTab = ref('all');
const addGroupDialogVisible = ref(false);
const addGroupForm = ref({
  groupName: '',
  groupType: '班级'
});

const handleClick = (groupName: string) => {
  console.log(`Clicked on ${groupName} assignment`);
};

const changeTab = (tab: string) => {
  currentTab.value = tab;
};

const filteredGroupData = computed(() => {
  if (currentTab.value === 'all') {
    return groupData.value;
  } else if (currentTab.value === 'class') {
    return groupData.value.filter(item => item.group.groupType === '班级');
  } else if (currentTab.value === 'team') {
    return groupData.value.filter(item => item.group.groupType === '战队');
  }
  return [];
});

const showAddGroupDialog = () => {
  addGroupDialogVisible.value = true;
};

const handleAddGroup = async () => {
  if (!addGroupForm.value.groupName.trim()) {
    ElMessage.warning('请输入组名');
    return;
  }

  adding.value = true;
  try {
    const res = await Group.addGroup({
      groupName: addGroupForm.value.groupName,
      groupType: addGroupForm.value.groupType
    });

    if (res.code === 200) {
      ElMessage.success('新增组成功');
      addGroupDialogVisible.value = false;
      fetchGroupData();
    } else {
      ElMessage.error(res.msg || '新增组失败');
    }
  } catch (error) {
    ElMessage.error('请求出错，请稍后重试');
    console.error('新增组出错:', error);
  } finally {
    adding.value = false;
  }
};

const handleDeleteGroup = (groupId: string, groupName: string) => {
  ElMessageBox.confirm(
      `确定要删除组 "${groupName}" 吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    deletingId.value = groupId;
    try {
      const res = await Group.deleteGroup(groupId);
      if (res.code === 200) {
        ElMessage.success('删除成功');
        fetchGroupData();
      } else {
        ElMessage.error(res.msg || '删除失败');
      }
    } catch (error) {
      ElMessage.error('删除出错');
      console.error('删除组出错:', error);
    } finally {
      deletingId.value = '';
    }
  }).catch(() => {
    // 用户点击取消
  });
};

const openUserSelection = async (groupId: string) => {
  currentGroupId.value = groupId;
  selectedUserIds.value = [];
  searchQuery.value = '';
  try {
    const res = await Alluser.getAllStudent();
    if (res.code === 200) {
      allUserList.value = res.data;
      filteredUserList.value = [...res.data];
      userDialogVisible.value = true;
    } else {
      ElMessage.error(res.msg || '获取用户列表失败');
    }
  } catch (error) {
    ElMessage.error('获取用户列表出错');
    console.error('获取用户列表出错:', error);
  }
};

const handleSearch = () => {
  if (!searchQuery.value) {
    filteredUserList.value = [...allUserList.value];
    return;
  }

  const query = searchQuery.value.toLowerCase();
  filteredUserList.value = allUserList.value.filter(user =>
      user.userName.toLowerCase().includes(query)
  );
};

const toggleUserSelection = (userId: number) => {
  const index = selectedUserIds.value.indexOf(userId);
  if (index === -1) {
    selectedUserIds.value.push(userId);
  } else {
    selectedUserIds.value.splice(index, 1);
  }
};

const confirmAddUsers = async () => {
  if (selectedUserIds.value.length === 0) {
    ElMessage.warning('请至少选择一个用户');
    return;
  }

  try {
    const res = await Group.addUsersToGroup({
      groupId: Number(currentGroupId.value),
      userIds: selectedUserIds.value
    });

    if (res.code === 200) {
      ElMessage.success('添加用户成功');
      userDialogVisible.value = false;
      fetchGroupData();
    } else {
      ElMessage.error(res.msg || '添加用户失败');
    }
  } catch (error) {
    ElMessage.error('添加用户出错');
    console.error('添加用户出错:', error);
  }
};

const fetchGroupData = async () => {
  try {
    const res = await Group.getAllGroup();
    if (res.code === 200) {
      groupData.value = res.data;
    } else {
      console.error('Failed to fetch group data:', res.msg);
    }
  } catch (error) {
    console.error('Error fetching group data:', error);
  }
};

onMounted(() => {
  fetchGroupData();
});
</script>

<style scoped>
.group-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
}

.group-tabs {
  margin-bottom: 20px;
}

.group-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.user-card {
  width: 120px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.user-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-size: 12px;
  text-align: center;
}

.add-user-card {
  width: 120px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed var(--el-border-color);
  cursor: pointer;
}

.add-user-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: var(--el-text-color-secondary);
}

.select-user-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  max-height: 400px;
  overflow-y: auto;
  padding: 10px 0;
}

.select-user-card {
  width: 120px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.select-user-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.is-selected {
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}
</style>
